//const axios = require('axios');


let cardGroup;
let targetCardGroup;
//let staticCardGroup;
let staticCardCount = 0;
let ifGenerating = false;
let mascot;
let mascotImg;
//let answerText = "来试试看吧";

const layoutList = ["math", "predecessor", "poetry"];
let currentLayout = "math";
let gameStatus = "default";
const attachedDistance = 100;


let gui;
var 卡牌文本 = '';
var 点击语音 = '';
var 正确答案 = '';
var 答对语音 = '';
var 答错语音 = '';
var 游戏名称 = '';
var 游戏描述 = '';
var 初始语音 = '';

let inputBox;
let submitButton;
let confirmButton;
let cancelButton;
let editButton;
let deleteButton;
let confirmDeleteButton;
let cancelDeleteButton;
let publishButton;
let generationList;
let newText;
let cardMenu;
let mainMenu;
let menu;
let confirmMenu;
let confirmText;
let bgSprite;
let exitEditSprite;

let currentCard = null;
let currentTarget = null;
let ifEditing = false; // 初始状态为未编辑
let dragOffsetX,dragOffsetY;
let confirmContext;
let inputText;

let start_audio= '';
let levelInfo;

const cardInfo = [{
  title:"8的加法",
  desprition: "十以内的加法",
  code:"set_meta({start_audio: \"找规律填数，公差为2，填3个空位\"});\nspawn_card({text:\"数字1\",x:100,y:230,clickedText:\"数字1\"});\nspawn_card({text:\"数字3\",x:200,y:230,clickedText:\"数字3\"});\nspawn_card({text:\"数字5\",x:300,y:230,clickedText:\"数字5\"});\nspawn_card({text:\"数字9\",x:500,y:230,clickedText:\"数字9\"});\nspawn_card({text:\"数字11\",x:600,y:230,clickedText:\"数字11\"});\nset_target({answer:\"数字7\",x:400,y:230,correct_text:\"答对了 真棒\",error_text:\"不是哦,再想想\"});\nset_target({answer:\"数字13\",x:700,y:230,correct_text:\"答对了 真棒\",error_text:\"不是哦,再想想\"});\nspawn_card({text:\"数字7\",clickedText:\"数字7\"});\nspawn_card({text:\"数字13\",clickedText:\"数字13\"});\nspawn_card({text:\"数字15\",clickedText:\"数字15\"});\nspawn_card({text:\"数字6\",clickedText:\"数字6\"});\nspawn_card({text:\"数字12\",clickedText:\"数字12\"});\nspawn_card({text:\"数字4\",clickedText:\"数字4\"});\n"},
  {
    title:"8的前后",
    desprition: "数字的前后关系",
    code:"set_meta({start_audio: \"找规律填数，公差为2，填3个空位\"});\nspawn_card({text:\"数字1\",x:100,y:230,clickedText:\"数字1\"});\nspawn_card({text:\"数字3\",x:200,y:230,clickedText:\"数字3\"});\nspawn_card({text:\"数字5\",x:300,y:230,clickedText:\"数字5\"});\nspawn_card({text:\"数字9\",x:500,y:230,clickedText:\"数字9\"});\nspawn_card({text:\"数字11\",x:600,y:230,clickedText:\"数字11\"});\nset_target({answer:\"数字7\",x:400,y:230,correct_text:\"答对了 真棒\",error_text:\"不是哦,再想想\"});\nset_target({answer:\"数字13\",x:700,y:230,correct_text:\"答对了 真棒\",error_text:\"不是哦,再想想\"});\nspawn_card({text:\"数字7\",clickedText:\"数字7\"});\nspawn_card({text:\"数字13\",clickedText:\"数字13\"});\nspawn_card({text:\"数字15\",clickedText:\"数字15\"});\nspawn_card({text:\"数字6\",clickedText:\"数字6\"});\nspawn_card({text:\"数字12\",clickedText:\"数字12\"});\nspawn_card({text:\"数字4\",clickedText:\"数字4\"});\n"},
  {
    title:"学习一下静夜思",
    desprition: "古诗诗句排序",
    code:"set_meta({start_audio: \"找规律填数，公差为2，填3个空位\"});\nspawn_card({text:\"数字1\",x:100,y:230,clickedText:\"数字1\"});\nspawn_card({text:\"数字3\",x:200,y:230,clickedText:\"数字3\"});\nspawn_card({text:\"数字5\",x:300,y:230,clickedText:\"数字5\"});\nspawn_card({text:\"数字9\",x:500,y:230,clickedText:\"数字9\"});\nspawn_card({text:\"数字11\",x:600,y:230,clickedText:\"数字11\"});\nset_target({answer:\"数字7\",x:400,y:230,correct_text:\"答对了 真棒\",error_text:\"不是哦,再想想\"});\nset_target({answer:\"数字13\",x:700,y:230,correct_text:\"答对了 真棒\",error_text:\"不是哦,再想想\"});\nspawn_card({text:\"数字7\",clickedText:\"数字7\"});\nspawn_card({text:\"数字13\",clickedText:\"数字13\"});\nspawn_card({text:\"数字15\",clickedText:\"数字15\"});\nspawn_card({text:\"数字6\",clickedText:\"数字6\"});\nspawn_card({text:\"数字12\",clickedText:\"数字12\"});\nspawn_card({text:\"数字4\",clickedText:\"数字4\"});\n"
}

];

const colorPalette = {
  cardBg: [254, 241, 206],
  targetBg: [240, 244, 252],
  black: [0, 0, 0],
  staticCardBg: [240, 244, 252],
};


function preload() {
  // 吉祥物
  mascotImg = loadImage("../images/mascot.png");
}

function setup() {
  createCanvas(800, 600); // 使用整个窗口高度
 
  const canvas1 = select('canvas');

  // 添加 mousePressed 事件监听器
  canvas1.mousePressed = function() {
    console.log('Canvas mouse pressed');
  };

  
  inputBox = select('#inputBox');
  submitButton = select('#submitButton');
  confirmButton = select('#confirmButton');
  cancelButton = select('#cancelButton');
  generationList = select('#generationList');
  newText = select('#newText');
  cardMenu = select('#card-menu');
  mainMenu = select('#main-menu');
  editButton = select('#editButton');
  deleteButton = select('#deleteButton');
  confirmDeleteButton =  select('#confirmDeleteButton'); 
  cancelDeleteButton = select('#cancelDeleteButton')
  publishButton = select('#publishButton');
  confirmMenu = select('#confirm-menu');
  confirmText = select('#confirmText');
  
  
  createPromptInput();
  // bgSprite = new Sprite(0,300,800,600);
  // bgSprite.layer =0.1;
  // bgSprite.overlaps(allSprites);
  // bgSprite.strokeWeight =0;
  // bgSprite.color = "#000000";


  //创建卡牌与目标初始化
  cardGroup = new Group();
  cardGroup.w = 120*0.62;
  cardGroup.h = 120;
  cardGroup.textSize = 20;
  cardGroup.layer = 2;
  

  targetCardGroup = new Group();
  targetCardGroup.w = 120*0.62*1.1;
  targetCardGroup.h = 120*1.1;
  targetCardGroup.type = 'target';
  targetCardGroup.text = '?';
  targetCardGroup.correct_text = '';
  targetCardGroup.error_text = '';
  targetCardGroup.textSize = 30;
  targetCardGroup.layer = 1;


  ////////////////////////////////////////////////////////////


  // 创建吉祥物
  mascot = createSprite(width / 4, 30, 100, 100);
  mascot.addImage(mascotImg);
  mascot.scale = 0.3;
  mascot.rotation = 180; // 设置旋转角度为180度
  mascot.update = ()=>{
    mascot.scale = 0.32 + 0.02 * Math.sin(frameCount * 0.05);
  }
  
  //mascot.collider = "none";

  // exit edit sprite
  exitEditSprite = new Sprite(0,0,20,20);
  exitEditSprite.image = '⬅️';
  exitEditSprite.overlaps(allSprites);
  exitEditSprite.layer = 3;
  exitEditSprite.update = ()=>{
    exitEditSprite.rotation=0;
    if (gameStatus === 'edit') exitEditSprite.visible = false;
    else exitEditSprite.visible = false;
    if (currentCard!==null) {exitEditSprite.x = currentCard.x; exitEditSprite.y = currentCard.y-90 }
    else if (currentTarget!==null) {exitEditSprite.x = currentTarget.x; exitEditSprite.y = currentTarget.y-90 };
  }
  exitEditSprite.visible = false;
  gui = createGui('编辑');
  gui.addGlobals('游戏名称','游戏描述','卡牌文本', '点击语音', '正确答案', '答对语音', '答错语音', '初始语音');
  gui.setPosition(0.6*windowWidth, 50);
  gui.show();
  // initial cards
  let randomLevel = Math.floor(random(0,cardInfo.length));
  levelInfo = cardInfo[randomLevel];
  startLevel(levelInfo);
 



}

function switchGUI(current)
{
  const cardGUIControls = ['卡牌文本','点击语音'];
  const targetGUIControls = ['正确答案', '答对语音', '答错语音'];
  const metaGUIControls = ['游戏名称','游戏描述','初始语音']
  if (current === 'target')
  {
    for (let control of targetGUIControls) {
        gui.prototype.showControl(control);
    }
    for (let control of cardGUIControls) {
      gui.prototype.hideControl(control);
    }
    for (let control of metaGUIControls) {
      gui.prototype.hideControl(control);
    }
  } 
  else if (current === 'card') {
    for (let control of cardGUIControls) {
        gui.prototype.showControl(control);
    }
    for (let control of targetGUIControls) {
      gui.prototype.hideControl(control);
    }
    for (let control of metaGUIControls) {
      gui.prototype.hideControl(control);
    }
  }
  else if (current === 'meta') {
    for (let control of metaGUIControls) {
        gui.prototype.showControl(control);
    }
    for (let control of cardGUIControls) {
      gui.prototype.hideControl(control);
    }
    for (let control of targetGUIControls) {
      gui.prototype.hideControl(control);
    }
  }

}

function draw() {
  
  clear();
  background(240);
  push()
  fill(230);
  noStroke();
  rect(0,600-150,800,150);
  pop()

  if (gameStatus === 'edit')
  {
    push()
    stroke(200,200,200);
    drawingContext.setLineDash([10, 5])
    for (let x = 0; x <= width; x += 50) {
      line(x, 0, x, height);
    }
    for (let y = 0; y <= height; y += 50) {
      line(0, y, width, y);
    }
    stroke(200,200,200,100);
    drawingContext.setLineDash([1, 1])
    for (let x = 0; x <= width; x += 10) {
      line(x, 0, x, height);
    }
    for (let y = 0; y <= height; y += 10) {
      line(0, y, width, y);
    }
    drawingContext.setLineDash([])
    pop()

  }

  if (gameStatus === 'edit') 
  {
      mainMenu.addClass('hidden');
      cardMenu.removeClass('hidden');
      confirmMenu.addClass('hidden');
  }
  else if (gameStatus === 'default')
  {
     mainMenu.removeClass('hidden');
      cardMenu.addClass('hidden');
      confirmMenu.addClass('hidden');

  }
  else if (gameStatus.includes ('waiting') )
  {
    mainMenu.addClass('hidden');
    cardMenu.addClass('hidden');
    confirmMenu.addClass('hidden');
  }
  else if (gameStatus.includes('confirm'))
  {
    mainMenu.addClass('hidden');
    confirmMenu.removeClass('hidden');

  }


  if (gameStatus.includes('waiting') )
  {
    textSize(30);
    
    text('处理中，请稍等'+'.'.repeat(frameCount/10%4),width/2-100,height/2);
    
  }
  else{
    textSize(14 + 0.5 * Math.sin(frameCount * 0.05));
    textAlign(LEFT);
    text(start_audio, width*0.3, height*0.08);

  }
  
  

  if (currentCard!==null)
  {

    currentCard.text = 卡牌文本;
    currentCard.clickedText = 点击语音;



  }
  if (currentTarget !==null)
  {
    currentTarget.answer = 正确答案;
    currentTarget.correct_text = 答对语音;
    currentTarget.error_text = 答错语音;
  }
  levelInfo.title =  游戏名称

  levelInfo.desprition=游戏描述


}


function exitEdit()
{
  let c;
  if (currentCard!==null) c=currentCard;
  else c=currentTarget;
  c.collides(allSprites);
  switchGUI('meta')
  currentTarget= null;
  currentCard = null;
  gameStatus = 'default';

}

function enterEdit(currentSelected)
{
  gameStatus = 'edit'
  currentSelected.overlaps(allSprites);
  dragOffsetX = currentSelected.x - mouse.x;
  dragOffsetY = currentSelected.y - mouse.y;
  if (currentSelected.type === 'target')
  {
    setTargetEditPanel(currentSelected);
    switchGUI('target')
  }
  else{
    setCardEditPanel(currentSelected);
    switchGUI('card')
  }


}


function mousePressed()
{
  console.log(gameStatus);
  if(gameStatus === 'edit')
  {
    if (currentCard!==null)switchGUI('card');
    else if (currentTarget!==null) switchGUI('target');
    if (exitEditSprite.mouse.pressing())
      {
        exitEdit()
        
      }    
    //return;
  }
 
  console.log('enter')
  let ifSelectCard = false;
  for (let card of cardGroup)
  {
    if (card.mouse.pressing()) 
    {
      ifSelectCard = true;
      currentCard = card;
      currentTarget = null;
      enterEdit(currentCard);
      
      
    }
  }
  if (!ifSelectCard)
  {
    for (let target of targetCardGroup)
    {
      if (target.mouse.pressing()) 
        {
          ifSelectCard = true;
          
          currentTarget= target;
          currentCard = null;
          enterEdit(currentTarget);
        }
    }
  }
}

function setCardEditPanel(c)
{
  if (c===null)
  {
    //gui.prototype.setValuesFromJSON({'卡牌文本':''});
    //卡牌文本 = ' ';
  }
  else 
  {
    console.log(c.text);
    gui.prototype.setValuesFromJSON({'卡牌文本':c.text, "点击语音":c.clickedText});
    //卡牌文本 = e.text; // 
  }
}

function setMetaPanel()
{
  gui.prototype.setValuesFromJSON({'游戏名称':levelInfo.title, '游戏描述':levelInfo.desprition,'初始语音':start_audio});
}

function setTargetEditPanel(t)
{
  if (t===null)
  {
    //gui.prototype.setValuesFromJSON({'卡牌文本':''});
    //卡牌文本 = ' ';
  }
  else 
  {
    console.log(t.text);
    gui.prototype.setValuesFromJSON({'正确答案':t.answer, "答对语音":t.correct_text,"答错语音":t.error_text});
    //卡牌文本 = e.text; // 
  }
}

function createPromptInput() {
 
  generationList.changed(() => {
    switch (generationList.value()) {
      case '游戏':
        inputBox.attribute('placeholder', '游戏的一句话描述（注意：新游戏会覆盖未发布游戏）');
        generationList.style('background-color', '#ff5733');
        break;
      case '代码':
      inputBox.attribute('placeholder', '通过代码来生成新游戏（注意：新游戏会覆盖未发布游戏）');
      generationList.style('background-color', '#009122');
      break;
      case '题目卡':
        inputBox.attribute('placeholder', '题目卡标题');
        generationList.style('background-color', '#f0f4fc');
        generationList.style('color', 'rgba(0, 0, 0, 0.832)');
        
        break;
      case '候选卡':
        inputBox.attribute('placeholder', '候选卡标题');
        generationList.style('background-color', '#fef1ce');
        generationList.style('color', 'rgba(0, 0, 0, 0.832)');
        break;
      case '目标答案':
        inputBox.attribute('placeholder', '目标正确答案');
        generationList.style('background-color', '#f0f4fc');
        generationList.style('color', 'rgba(0, 0, 0, 0.832)');
        break;
      default:
        inputBox.attribute('placeholder', '请输入描述');
    }
  });

  submitButton.mousePressed(() => {
    // Toggle hidden class for confirm and cancel buttons
    inputText = inputBox.value();
      if (inputText.trim() === "") {
        console.log("输入为空，请输入内容");
        alert("输入为空，请输入内容");
        return;
      }
    if(generationList.value()==='游戏' || generationList.value()==='代码')
    {
      gameStatus = 'confirm.generate';
      // mainMenu.addClass('hidden');
      // confirmMenu.removeClass('hidden');
      confirmText.html('确定生成新游戏？将丢目前未发布草稿');
    }
    else
    {
      
      inputBox.value('');
      switch (generationList.value()) {
        case '题目卡':
          console.log("Generating card with title:", inputText);
         // spawn_card({text:inputText,x:random(100,700),y:random(50,400)});
          spawn_card({text:inputText,x:100,y:100});
          break;
        case '候选卡':
          console.log("Generating candidate card with title:", inputText);
          spawn_card({text:inputText});
          break;
        case '目标答案':
          console.log("Generating target answer with description:", inputText);
          set_target({answer:inputText,x:100,y:350});
          break;
        default:
          console.log("Unknown generation type:", generationList.value());
      }

    }
    
  });

  confirmButton.mousePressed(() => {

    
    inputBox.value('');
    // init level
    if(gameStatus === 'confirm.generate')
    {
      if (generationList.value()==='代码')
      {
        clearLevel();
        try {
          
          eval(inputText);
          setMetaPanel();
          switchGUI('meta')
        } catch (error) {
          console.error("Error executing code:", error);
          alert("代码执行出错，请检查代码是否正确。");
        }
        gameStatus = 'default';

      }
      else if  (generationList.value()==='游戏')
      {
        clearLevel();
        gui.hide();
        gameStatus = 'waiting.generatingCode';
        //auto_card(inputText);
        sendLevelQuery(inputText)
        console.log("Generating game with description:", inputText);

      }

      

    }
    else if (gameStatus ==='confirm.publish')
    {
      
      let code = saveCode();     
      let leveData = saveLevel();
      gameStatus = 'waiting.publishing';
      uploadLevel(leveData);

      //clearLevel();
      

      //setTimeout(()=>{eval(code);saveLevel();gameStatus = 'default';},1000);

    }
  });

  cancelButton.mousePressed(() => {
     gameStatus = 'default';
  });

  editButton.mousePressed(()=>{
    exitEdit();
  });

  deleteButton.mousePressed(() => {
    // Toggle hidden class for confirm and cancel buttons
    gameStatus = 'edit'
    confirmDeleteButton.removeClass('hidden');
    cancelDeleteButton.removeClass('hidden');
    deleteButton.addClass('hidden');
    editButton.addClass('hidden');
  });

  cancelDeleteButton.mousePressed(() => {
    // Toggle hidden class for confirm and cancel buttons
    confirmDeleteButton.addClass('hidden');
    cancelDeleteButton.addClass('hidden');
    deleteButton.removeClass('hidden');
    editButton.removeClass('hidden');
    gameStatus = 'edit'
  });

  confirmDeleteButton.mousePressed(() => {
    gameStatus = 'default'
    if (currentCard !== null) {currentCard.remove();currentCard = null; }
    else if (currentTarget !== null) {currentTarget.remove();currentTarget = null; }
    // Toggle hidden class for confirm and cancel buttons
    confirmDeleteButton.addClass('hidden');
    cancelDeleteButton.addClass('hidden');
    deleteButton.removeClass('hidden');
    editButton.removeClass('hidden');
  });

  publishButton.mousePressed(()=>{
    if (levelInfo.title ==='') {alert("游戏名称不可为空");return}
    if (targetCardGroup.length ===0){alert("至少有一个游戏目标");return}
    if (cardGroup.length ===0){alert("至少有一张卡牌");return}
    
    gameStatus = 'confirm.publish';
    mainMenu.addClass('hidden');
    confirmMenu.removeClass('hidden');
    confirmText.html('确认发布游戏？确认后将不可撤回');
  })
  
}



// function auto_card(message) {
//   let agentCard = new P5GLM();
//   agentCard.setModel("glm-4-plus");
//   let cardDescriptions = cardInfo.map((info, index) => `${index+1}. ${info.desprition}`).join('\n');
//   agentCard.send(`你是一个卡牌游戏设计师，可以根据用户输入选择最适合的卡牌布局：#用户输入：${message} #卡牌布局：\n${cardDescriptions} #输出格式：只输出数字序号，不输出其他文字或解释`);

//   agentCard.onComplete = (response) => {
//     console.log(response);
//     let layoutIndex = parseInt(response);
//     if (layoutIndex >= 1 && layoutIndex <= cardInfo.length) {
//       currentLayout = cardInfo[layoutIndex - 1].layout;
//       let agentGenerateCard = new P5GLM();
//       agentGenerateCard.setModel("glm-4-plus");
//       agentGenerateCard.send(`你是一个卡牌游戏设计师，可以根据用户输入生成卡牌布局,一定注意你只能生成一道题：#用户输入：${message} #参考卡牌布局：${cardInfo[layoutIndex-1].desprition} ${cardInfo[layoutIndex - 1].code} #输出格式：只输出js代码，其他内容以注释方式输出`);
//       agentGenerateCard.onComplete = (response) => {
//         // Remove the leading and trailing backticks and any comments
//         let cleanedResponse = response.replace(/^```javascript\s*/, '').replace(/\s*```$/, '');
//         // Remove all comments
//         cleanedResponse = cleanedResponse.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
//         // Remove any remaining non-code text
//         cleanedResponse = cleanedResponse.replace(/^\s*\/\/.*$/gm, '').replace(/^\s*\/\*[\s\S]*?\*\/\s*$/gm, '');
//         try {
//           console.log(cleanedResponse)
//             gui.show();
//             mainMenu.removeClass('hidden');
//             gameStatus = 'defalt';
//             eval(cleanedResponse);
//             levelInfo.title = '';
//             levelInfo.desprition = "";
//             setMetaPanel();
//         } catch (error) {
//             console.error("Error executing cleaned code:", error);
//         }
//       }
     
//     }
//   };
  
// }



function spawn_card(cardInfo) {
  let x = cardInfo.x !== undefined ? cardInfo.x : -1;
  let y = cardInfo.y !== undefined ? cardInfo.y : -1;
 
  let newCard = new cardGroup.Sprite();
  if (x === -1 || y === -1){
    newCard.type = 'card'
    newCard.x = (staticCardCount+1)*120*0.62*1.2;
    newCard.y = 600-150/2;
    staticCardCount++;
  }
  else 
  {
     newCard.type = 'staticCard'
     newCard.x = x;
     newCard.y = y;
  }
  
  newCard.text = cardInfo.text;
  newCard.clickedText = cardInfo.clickedText === undefined?cardInfo.text: cardInfo.clickedText;
  newCard.draw = () => {drawCard(newCard)};
  newCard.update = ()=>{
    newCard.rotation=0; 
    dragCard(newCard);
    attachGrid(newCard);
  }

 
}

function set_target(targetInfo) {
  if (targetInfo.x===undefined || targetInfo.y === undefined || targetInfo.answer=== undefined ) return;
  let newTarget = new targetCardGroup.Sprite();

  newTarget.type = 'target' 
  newTarget.x = targetInfo.x;
  newTarget.y = targetInfo.y;
  newTarget.answer = targetInfo.answer;
  if (targetInfo.correct_text!==undefined) newTarget.correct_text = targetInfo.correct_text;
  if (targetInfo.error_text!==undefined) newTarget.error_text = targetInfo.error_text;

  newTarget.draw = () => {drawCard(newTarget)};
  newTarget.update = ()=>{
    newTarget.rotation=0; 
    dragCard(newTarget);
    attachGrid(newTarget)
  }

}

function dragCard(c)
{
  if (gameStatus!=='edit'|| (c !== currentTarget && c!==currentCard)) return
  if (c.mouse.pressing())
  {

    c.x = mouse.x + dragOffsetX;
    c.y = mouse.y + dragOffsetY;

  }
}

function attachGrid(c)
{
  const step = 10;
  c.x = Math.round(c.x / step) * step;
  c.y = Math.round(c.y / step) * step;
  c.x = constrain(c.x, 0, 800);
  if (c.type === 'target' || c.type === 'staticCard' ) c.y = constrain(c.y, 0, 450);
  else if (c.type ==='card') c.y = (450+600)/2
 
 
  
}

function drawCard(c)
{
  push();
  if (c.type === 'card') fill(colorPalette.cardBg[0],colorPalette.cardBg[1],colorPalette.cardBg[2]);
  else if (c.type === 'staticCard' || c.type === 'target') fill(colorPalette.targetBg[0],colorPalette.targetBg[1],colorPalette.targetBg[2]);

  push()
  if (c.type === 'target') drawingContext.setLineDash([10, 5]);
  if (c!==currentCard && c!=currentTarget) 
    {
      if (gameStatus === 'edit') stroke(200,200,200);
      else stroke(0,0,0);
    }
  else {strokeWeight(3);stroke(0,255,0);}
  rect(0, 0, c.width, c.height, 10);
  if (c.type === 'target') drawingContext.setLineDash([]);
  pop();

  // 文本
  if (gameStatus === 'edit' && c!==currentCard && c!==currentTarget) fill(200,200,200);
  else fill(0);
  textAlign(CENTER, CENTER);
  let ratio = map(c.text.length, 1, 5, 2, 1);
  textSize(c.textSize*ratio<12?12:c.textSize*ratio);
  textWrap(CHAR);
  textStyle(NORMAL);
  text(c.text, 0, 0, c.width, c.height);  
  pop()
}

function saveCode()
{

  let code = '';
  code += `set_meta({start_audio: "${start_audio}"});\n`;
  for (let card of cardGroup) {
    if (card.type === 'staticCard') {
      let cardParams = {text: card.text, x: card.x, y: card.y};
      if (card.clickedText) cardParams.clickedText = card.clickedText;
      code += `spawn_card(${JSON.stringify(cardParams).replace(/"([^"]+)":/g, '$1:')});\n`;
    }
  }
  for (let target of targetCardGroup) {
    let targetParams = {answer: target.answer, x: target.x, y: target.y};
    if (target.correct_text) targetParams.correct_text = target.correct_text;
    if (target.error_text) targetParams.error_text = target.error_text;
    code += `set_target(${JSON.stringify(targetParams).replace(/"([^"]+)":/g, '$1:')});\n`;
  }
  for (let card of cardGroup) {
    if (card.type === 'card') {
      let cardParams = {text: card.text};
      if (card.clickedText) cardParams.clickedText = card.clickedText;
      code += `spawn_card(${JSON.stringify(cardParams).replace(/"([^"]+)":/g, '$1:')});\n`;
    }
  }
  console.log(code);
  return code;
}

function saveLevel()
{
  let levelData = {
    title: 游戏名称,
    desprition: 游戏描述,
    code: saveCode()
  };
  console.log("Generated level data:", levelData);

  // Save the level data as a JSON file with timestamp in the filename
  // const blob = new Blob([JSON.stringify(levelData, null, 2)], { type: 'application/json' });
  // const url = URL.createObjectURL(blob);
  // const a = document.createElement('a');
  // a.href = url;
  // const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  // a.download = `levelData_${timestamp}.json`;
  // document.body.appendChild(a);
  // a.click();
  // document.body.removeChild(a);
  // URL.revokeObjectURL(url);

  return levelData

}

function clearLevel()
{
  cardGroup.amount =0;
  targetCardGroup.amount =0;
  staticCardCount = 0;
  levelInfo.title = '';
  levelInfo.desprition = '';
  start_audio = '';
  

  gameStatus = 'default';

}

function set_meta(config) {
  if (config.start_audio !== undefined) {
    start_audio = config.start_audio;
  }
}

function startLevel(code)
{
  gui.show();
  gameStatus = 'default';
  levelInfo.title = '';
  levelInfo.desprition = "";
  //levelInfo = levelData;
  eval(code);
  setMetaPanel();
  switchGUI('meta')
}

// new save and publish logic 


// function createLevel 
// gameStatue = dg




////////////////// client - server communication interface

async function sendLevelQuery(query) {
 
  try {
    const codeResult = await getCode(query, "DeepSeek");
    console.log("Generated Code:", codeResult);
    onReceiveLevelData(codeResult.js_code);
  } catch (error) {
    console.error("Error generating code:", error);
  }
}




function onReceiveLevelData(code)
{
  // 这个是 sendLevelQuery(query) 收到 levelData 回复时执行的 callback 函数，不需要修改
  // 收到levelData的前端逻辑
  clearLevel();
  startLevel(code);
  
}





function onReceiveLevelAssetData(assetData)
{

  // 这个是 publishLevel(levelData) 收到 assetData 回复时执行的 callback 函数
  // 此函处理流式美化界面的逻辑，目前暂时不开发，等assetData数据完善时再开发

}

const BASE_URL = "http://106.54.192.233:8080"; // 替换为实际后台地址
// const GET_ALL_LEVELS_URL = `${BASE_URL}/getAllLevels`;
// const GET_LEVEL_LIST_URL = `${BASE_URL}/getLevelList`; // 正确的获取单个 Level 代码接口
// const UPLOAD_SAMPLE_FILE_URL = `${BASE_URL}/updateSampleFile`; // 上传文件接口
const GET_CODE_URL = `${BASE_URL}/getCode`;

async function getCode(query, modelChoice) {
  const payload = {
      query: query,
      mode: "js", // mode 固定为 "js"
      model_choice: modelChoice
  };

  try {
      const response = await fetch(GET_CODE_URL, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
      });

      if (response.status === 200) {
          const result = await response.json();
          if (result.error) {
              return `生成失败：${result.error}`;
          }
          return result; // 返回生成的代码
      } else {
          const text = await response.text();
          return `请求失败，状态码：${response.status}, 响应：${text}`;
      }
  } catch (e) {
      return `生成代码时发生错误：${e}`;
  }
}



// 定义 API 地址
const UPLOAD_LEVEL_URL = "http://106.54.192.233:8080/uploadLevel"; // 替换为实际后台地址

// 批量上传 JSON 文件的函数
async function uploadLevel(levelData) {
    // 遍历指定文件夹下的所有 JSON 文件

      try {
          // 读取 JSON 文件
         
          // 构建上传的 payload
          const payload = {
              title: levelData.title,
              author: 'lulu',
              query: levelData.desprition,
              description: levelData.desprition, 
              code: levelData.code,
              data: levelData.code,
              overwrite: false
          };

          // 发送 POST 请求
          const response = await axios.post(UPLOAD_LEVEL_URL, payload);

          // 处理响应
          if (response.status === 200) {
              console.log(`文件上传成功:`, response.data);
              alert('发布成功')
          } else {
              console.log(`文件上传失败，状态码: ${response.status}, 响应:`, response.data);
              alert('发布未成功')
          }
          gameStatus = 'default';

          // return

      } catch (e) {
          console.log(`文件上传时发生错误:`, e);
      }
  }

